import { Injectable, Pipe } from '@angular/core';
import { Effect, Actions, ofType } from '@ngrx/effects';
import { of } from 'rxjs/observable/of';
import { catchError, map, mergeMap, switchMap } from 'rxjs/operators';

import { 
    DistrictActionTypes, 
    LoadDistrictsSuccess, 
    LoadDistrictsFail, 
    SelectDistrict, 
    SelectDistrictLoadFail, 
    SelectDistrictLoadSuccess,
    AutoLocateDistrictFail,
    AutoLocateDistrictSuccess
} from '../actions/districts.action';

import { RestapiAmapService } from '../../../ngx-ol/services/restapi-amap.service';
import { District, DistrictOptions, UserLocation } from '../../../ngx-ol/models';

@Injectable()
export class DistrictsEffects {

    constructor(
        private action$: Actions,
        private restapi: RestapiAmapService
    ) {}

    @Effect()
    loadDistricts$ = this.action$
        .pipe(
            ofType(DistrictActionTypes.LOAD_DISTRICTS),
            switchMap(() => {
                const options: DistrictOptions = {
                    subdistrict: 2,
                    extensions: 'base'
                };
                return this.restapi.district(options).pipe(
                    map((districts: District[]) => new LoadDistrictsSuccess(districts)),
                    catchError(error => of(new LoadDistrictsFail(error)))
                );
            })
        );
    
    @Effect()
    loadSelectDistrict$ = this.action$
        .pipe(
            ofType(DistrictActionTypes.SELECT_DISTRICT),
            mergeMap((action: SelectDistrict) => {
                return this.restapi.districtByAdcode(action.payload).pipe(
                    map((district: UserLocation) => new SelectDistrictLoadSuccess(district)),
                    catchError(error => of(new SelectDistrictLoadFail()))
                );
            })
        );
    @Effect()
    autoLocateDistrict$ = this.action$
        .pipe(
            ofType(DistrictActionTypes.AUTO_LOCATE_DISTRICT),
            switchMap(() => {
                return this.restapi.getLoaction().pipe(
                    map((district: UserLocation) => new AutoLocateDistrictSuccess(district)),
                    catchError(error => of(new AutoLocateDistrictFail()))
                );
            })
        );
    
    // @Effect()
    // InitDefaultDistrict$ = this.action$
    //     .pipe(
    //         ofType(DistrictActionTypes.INIT_DEFAULT_DISTRICT),
    //         mergeMap((action: InitDefaultDistrict) => {
    //             return this.restapi.districtByAdcode(action.payload).pipe(
    //                 map((district: District) => new LoadSelectDistrict(district)),
    //                 catchError(error => of(new LoadDistrictsFail(error)))
    //             );
    //         })
    //     );
}